namespace Maple.Branch.Tenants.EfCoreConfigurations
{
    using System;
    using Consts;
    using Entities;
    using JetBrains.Annotations;
    using Microsoft.EntityFrameworkCore;
    using Options;
    using Volo.Abp;
    using Volo.Abp.EntityFrameworkCore.Modeling;

    public static class TenantsModelBuilderExtensions
    {
        public static void ConfigureTenants(
            [NotNull] this ModelBuilder builder,
            [CanBeNull] Action<TenantsModelBuilderOption> optionsAction = null)
        {
            Check.NotNull(builder, nameof(builder));

            var options = new TenantsModelBuilderOption(
                DbOptions.Prefix,
                DbOptions.Schema
            );

            optionsAction?.Invoke(options);

            builder.Entity<Tenant>(b =>
            {
                b.ToTable(options.TablePrefix + nameof(Tenant), options.Schema);

                b.ConfigureByConvention();

                b.Property(t => t.Name).IsRequired().HasMaxLength(TenantConsts.MaxNameLength);

                b.HasMany(u => u.ConnectionStrings).WithOne().HasForeignKey(uc => uc.TenantId).IsRequired();

                b.HasIndex(u => u.Name);
            });

            builder.Entity<TenantConnectionString>(b =>
            {
                b.ToTable(options.TablePrefix + nameof(TenantConnectionString), options.Schema);

                b.ConfigureByConvention();

                b.HasKey(x => new { x.TenantId, x.Name });

                b.Property(cs => cs.Name).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxNameLength);
                b.Property(cs => cs.Value).IsRequired().HasMaxLength(TenantConnectionStringConsts.MaxValueLength);
            });
        }
    }
}
